<template>
	<div class="dis-ib">
    
    <el-dialog title="编辑图文"
      :visible.sync="dialogVisibleEditMpnews"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="80%" append-to-body>
      <div class="mpnewsEditArea">
        <div class="left_con">
          <div class="title_input">
            <el-input placeholder="在此输入标题" v-model="draft[current].title" clearable></el-input>
            <!-- 富文本框 -->
            <quill-editor ref="myQuillEditor2" :options="quillOption"
              v-model="draft[current].content"
              @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
              @ready="onEditorReady" @change="onEditorChange"
              class="editor" />

            <!-- 文件上传input 将它隐藏-->
            <el-upload class="avatar-uploader" name="img"
              :action="serverUrl"
              :data="fileUpload"
              :show-file-list="false"
              :before-upload="uploadBefore"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              >
            </el-upload>
          </div>
          <div class="add_fun dis-flex flex-lc">
            <div class="img-box face">
              <img v-if="draft[current].imgUrl" class="img-cover" :src="draft[current].imgUrl"/>
            </div>
            <el-upload class="upload-demo"
              :action="serverUrl"
              :data="fileUpload"
              :before-upload="uploadBefore"
              :on-success="uploadFaceSuccess"
              :on-error="uploadError"
              :show-file-list="false"
              ref="cover">
              <template v-if="!draft[current].imgUrl">
                <el-button type="text">添加封面图</el-button>
                建议尺寸：1068*455
              </template>
              <template v-else>
                <el-button type="text">更改封面图</el-button>
              </template>
            </el-upload>
          </div>
          <div class="add_fun dis-flex flex-sbc">
            <p class="appLabel">摘要：</p>
            <el-input type="textarea" class="input-textarea" autosize
              placeholder="选填" v-model="draft[current].digest" resize="none">
            </el-input>
          </div>
          <div class="add_fun dis-flex flex-sbc">
            <p class="appLabel">作者：</p>
            <el-input type="textarea" class="input-textarea" autosize
              placeholder="选填" v-model="draft[current].author" resize="none">
            </el-input>
          </div>
          
        </div><!--left-->
        <div class="right_con">
          <div class="onlyOne" v-if="draft.length == 1">
            <div class="item" @click="selectItem(0)">
              <div class="img-box face">
                <img class="img-cover" :src="draft[0].imgUrl" :alt="draft[0].title">
              </div>
              <div class="title text-overflow">{{ draft[0].title }}</div>
              <div class="desc text-overflow">{{ draft[0].digest }}</div>
            </div>
          </div>
          <div class="gtOne" v-else>
            <div :class="['item','item_'+ak,(current==ak)?'active':'']"
              v-for="(art,ak) in draft" :key="ak"  @click="selectItem(ak)">
              <div class="img-box face">
                <img class="img-cover" :src="art.imgUrl" :alt="art.title">
              </div>
              <div class="title text-overflow">{{ art.title }}</div>
              <div class="delete_mask">
                <i class="el-icon-delete-solid" @click="delMpnewsItem(ak)"></i>
              </div>
            </div>
          </div>
          <div class="add_btn" @click="addMpnewsItem()" v-show="draft.length < 7">
            <i class="el-icon-plus"></i>
          </div>
        </div><!--right缩略图-->
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <template v-if="isDev">
          <pre>{{ JSON.stringify(fileUpload,null,2) }}</pre>
        </template> -->
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import * as Quill from 'quill';

import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';

import resizeImage from 'quill-image-resize-module';//调整大小组件
console.log('%c [ resizeImage ]-117', 'font-size:13px; background:pink; color:#bf2c9f;', resizeImage)
import { ImageDrop } from 'quill-image-drop-module';//拖动加载图片组件

Quill.register('modules/imageResize', resizeImage);
Quill.register('modules/imageDrop', ImageDrop);

let fontSizeStyle = Quill.import('attributors/style/size');
fontSizeStyle.whitelist = ['12px', '14px', false, '18px', '20px', '24px']
Quill.register(fontSizeStyle, true)

import { toolbarOptions } from './quill.conf.js';//目前没用

export default {
  name:"mpnewsEdit",
  components:{
    quillEditor,Quill
  },
  data() {
    return {
      isDev:process.env.NODE_ENV == 'development',
      dialogVisibleEditMpnews:false,
      draft:[{
        detail_Id:0,//主键Id
        title:"",//标题
        digest:"",//摘要,描述
        author:"",//作者
        content_source_url:"",//点击 阅读原文跳转的页面连接
        content:"",//内容
        imgUrl:null,//缩略图URL
        thumb_media_id:null,//缩略图meidiaId
      }],
      defDraft:[{
        detail_Id:0,//主键Id
        title:"",//标题
        digest:"",//摘要,描述
        author:"",//作者
        content_source_url:"",//点击 阅读原文跳转的页面连接
        content:"",//内容
        imgUrl:null,//缩略图URL
        thumb_media_id:null,//缩略图meidiaId
      }],
      /*
        $store.draftMpnews 的副本,也是本组件的主体,上面的结构是 draftMpnews 的结构
        注意这里只接收 articles 部分,其他属性目前看来并不重要(msg只收取articles)
        发送消息前处理详见 7-sendOutArea.vue 的 sendBefore 方法
      */
      current:0,//基础指向,用来标记编辑到mpnews的索引,默认0
      quillOption: {
        // Some Quill options...
        placeholder: "请输入正文",
        //  富文本编辑器配置
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'image': function(value) {
                if (value) {
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            },
          },
          imageDrop: true,
          imageResize: {}
        },
        theme: 'snow'
      },
      fileUpload: { //附件上传
        file: null,
        token:''
      },
      serverUrl: 'http://upload.qiniup.com', //上传图片的地址
      qiniuaddr:'https://qiniuoss.chenxi618.com',
    }
  },
  computed:{
    ...mapState(['draftMpnews',]),
  },
  
  methods: {
    open(){//父级使用
      this.draftMpnews.articles.forEach((art) => {
        this.draft.push(JSON.parse(JSON.stringify(art)))
      });
      this.draft.splice(0,1);
      // this.currentTitle = this.draftMpnews.articles[0].title;
      this.dialogVisibleEditMpnews = true;
    },
    cancel(){
      this.current = 0;
      this.dialogVisibleEditMpnews = false;
    },
    confirm(){
      this.current = 0;
      this.$store.commit('setDraft',{
        type:'mpnews',
        obj:{
          // id:null,
          // esCompanyName:null,
          articles:this.draft
          // addTime:null
          // editTime:null
        }
      })
      this.draft.splice(0,this.draft.length)
      this.draft.push(this.defDraft)
      this.dialogVisibleEditMpnews = false;
    },
    selectItem(idx){
      this.current = idx;
      // 防止富文本框进入页面就显示指针
      this.$refs.myQuillEditor2.quill.enable(false);
      setTimeout(res=>{
        this.$refs.myQuillEditor2.quill.enable(true)
      },1000)
    },
    onEditorBlur(e){
      // this.imageTextList[this.selectIndex].abstractEmpty = this.$refs.myQuillEditor2.quill.getText(0, 50);
    },//失焦
    onEditorFocus(e){
      // document.getElementsByClassName('ql-toolbar')[0].style.display = "inline";
    },//获焦
    onEditorReady(quill){
      // console.log('editor ready!', quill)
    },
    onEditorChange(e){},

    
    uploadBefore(file) {
      if(file.type != "image/png" && file.type != "image/jpeg") {
        this.$message({
          message: '请上传正确的图片',
          type: 'warning'
        });
        return false;
      }
      this.quillUpdateImg = true;// 显示loading动画
      this.fileUpload.file = file;
      return this.$api.getQiniuToken().then(res=>{
        this.fileUpload.token = res.data.data;
      })
    },
    uploadSuccess(response,res,fileList){
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.myQuillEditor2.quill;
      // 上传成功所执行
      if ("key" in response) {
        // 获取光标所在位置
        let idx = quill.selection.savedRange.index;
        // 插入图片res为服务器返回的数据https://qiniuoss.chenxi618.com/loading.gif
        quill.insertEmbed(idx, 'image', `${this.qiniuaddr}/${response.key}`)
        // 光标移动至文本末端
        quill.setSelection(idx + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      this.quillUpdateImg = false;// loading动画消失
    },//富文本中 图片 上传成功后 写入富文本
    uploadFaceSuccess(response,res,fileList){
      if(!("key" in response)){ return }
      let self = this;
      let arg = Object.assign(
        this.$store.getters.getESID(false),
        {
          mediaType:'image',
          mediaName:'',//传文件的时候，需要这个mediaName，要带上前名后缀的文件名
          qiniuUrl:`${this.qiniuaddr}/${response.key}`
        }
      );
      this.$api.getGetMediaId(arg).then((res)=>{
        let tempMediaId = res.data.data;
        return {
          imgUrl:`${this.qiniuaddr}/${response.key}`,
          media_Id:tempMediaId,
        }
      }).then((res)=>{
        self.$set( this.draft[this.current], 'imgUrl',         res.imgUrl    );
        self.$set( this.draft[this.current], 'thumb_media_id', res.media_Id  );
      })
    },//封面 图片 上传成功后 set封面
    uploadError() {
      this.quillUpdateImg = false;// loading动画消失
      this.$message.error('图片插入失败')
    },

    addMpnewsItem() {
      let addObj = {
        "show":false,
        "title": "",
        "digest": "",
        "author": "",
        "content": "",
        "imgUrl": ""
      }
      this.draft.push(addObj)
      this.current = this.draft.length - 1;
    },// 手动增加图文列表
    delMpnewsItem() {
      if(this.current == (this.current.length - 1)) {
        this.draft.splice(this.current,1)
        this.current--
      }else {
        this.draft.splice(this.current,1)
      }
    },// 手动删除图文列表
  },
  beforeDestroy(){
    // this.$message({
    //   message:'draftMpnews'
    // })
    console.log('des');
  }
}
</script>

<style lang="less" scoped>
.dis-ib{
  display:inline-block;
}
img{
  max-width:100%;
}
.mpnewsEditArea{
  width:100%;
  @rw:unit( (268 + 40),px);
  .left_con{
    min-height:500px;
    margin-right:@rw;
  }
  .right_con{
    position: absolute;
    top:0;right:0;
    width:@rw;
    padding-left:40px;
  }
}
.left_con{
  .add_fun{
    padding:15px;
    border-bottom: 1px solid #d9d9d9;
    .input-textarea{
      flex:1 1 auto;
      position: relative;
      display: inline-block;
      vertical-align: bottom;
      font-size: 14px;
    }
  }
  .face{
    width:112px;height:48px;
    margin-right:20px;
  }
  .appLabel{
    flex:0 0 3em;
    width:3em;
  }
}
.right_con{
  .onlyOne{
    .face{
      height:114px;
      background-color:#ddd;
    }
    .title{
      text-align: left;
      font-size:16px;
      margin:10px 0;
      padding:0 12px;
      color:#111;
    }
    .desc{
      text-align: left;
      font-size:14px;
      padding:0 12px;
      color:#999;
    }
  }
  .gtOne{
    .item{
      text-align: left;
      font-size:16px;
      line-height:20px;
      height:60px;
      border:1px solid #e4e6e9;
      background-color:#fff;
      &.active{
        border-color:#0c4c7f;
      }
      .face{
        position: absolute;
        top:10px;bottom:10px;right:10px;
        width:40px;height:40px;
      }
      .title{
        text-align: left;
        line-height:40px;
        position: relative;
        padding-left:10px;
        padding-right:60px;
        padding-top:10px;
        padding-bottom:10px;

      }
      .delete_mask{
        display:none;
      }
      &:hover .delete_mask{
        display:block;
        position: absolute;
        bottom:0;left:0;right:0;
        text-align:right;
        padding:2px 10px 0;
        background-color:rgba(0,0,0,0.5);
        color:#999;
      }
    }
    .item_0{
      height:144px;
      .face{
        position: relative;
        top:0px;bottom:0px;left:0;right:0px;
        width:100%;height:144px;
      }
      .title{
        position: absolute;
        left:0;right:0;bottom:0;
        text-align: left;
        padding:20px 10px 10px;
        background-image: linear-gradient(-180deg,transparent,rgba(0,0,0,0.35));
        color:#fff;
      }
    }
  }
  .add_btn{
    text-align: center;
    font-size:16px;
    line-height:60px;
    height:60px;
    border:1px solid #e4e6e9;
    background-color:#fff;
  }
}

</style>

